using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Threading;

namespace MapCop.Test.Helpers
{
    public class TestFile : IDisposable
    {
        private bool _disposedValue = false;
        private string _resourceName;
        private string _fileName;

        public TestFile(string fileName, string resourceName)
        {
            _resourceName = resourceName;
            _fileName = fileName;

            Assembly a = Assembly.GetExecutingAssembly();
            using (Stream s = a.GetManifestResourceStream(_resourceName))
            {
                if (s == null) throw new Exception("Manifest Resource Stream " + _resourceName + " was not found.");

                using (StreamReader sr = new StreamReader(s))
                {
                    using (StreamWriter sw = File.CreateText(_fileName))
                    {
                        sw.Write(sr.ReadToEnd());
                        sw.Flush();
                    }
                }
            }
        }

        public string FileName
        {
            get
            {
                return _fileName;
            }
        }
        
        public string ResourceName
        {
            get
            {
                return _resourceName;
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposedValue)
            {
                if (disposing)
                {
                    if (File.Exists(_fileName))
                    {
                        try
                        {
                            File.Delete(_fileName);
                        }
                        catch (IOException ex)
                        {
                            Console.Write("Failed to delete {0}, waiting 500ms : {1}", _fileName, ex.ToString());
                            Thread.Sleep(500);
                            Dispose(true);
                        }
                    }
                }
            }
            this._disposedValue = true;
        }

        #region IDisposable Members

        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }

}
